<template>
  <div class="app-container">
    <!-- 高级查询 -->
    <el-form v-show="searchVisible" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="汇总自:">
        <el-select v-model="queryParams.jobMonthFr" filterable clearable size="mini">
          <el-option v-for="item in options.jobMonthList" :key="item.key" :label="item.label" :value="item.key" />
        </el-select>
      </el-form-item>
      <el-form-item label="至:">
        <el-select v-model="queryParams.jobMonthTo" filterable clearable size="mini">
          <el-option v-for="item in options.jobMonthList" :key="item.key" :label="item.label" :value="item.key" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="供应商编号:">
        <el-select v-model="queryParams.payCust" placeholder="请选择供应商编号" clearable size="small">
          <el-option v-for="option in options.supplierIdOptions" :key="option.id" :label="option.supplierName" :value="option.id" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="店铺:">
         <el-select v-model="queryParams.storeId" placeholder="请选择店铺" filterable clearable size="mini">
           <el-option v-for="option in options.storeOptions" :key="option.storeCode" :label="option.storeName" :value="option.storeCode" />
         </el-select>
      </el-form-item>
      <el-form-item label="商品名:">
        <el-input v-model="queryParams.cargoObjectName" size="mini" placeholder="请输入商品名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户SKU:">
        <el-input v-model="queryParams.custSkuId" size="mini" placeholder="请输入客户SKU" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户SPU:">
        <el-input v-model="queryParams.custSpuId" size="mini" placeholder="请输入客户SPU" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button v-loading="exportLoading" v-hasPermission="['accounting:accApSkuMonthlySettlement:search']" type="warning" icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
        <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
      </el-form-item>
      <!-- <el-form-item>
            <el-col :span="1.5">
              <span style="padding-left: 2px"><el-tag type="info">单品合计：{{ sumQty }}</el-tag></span>
              <span style="padding-left: 2px"><el-tag type="info">采购价合计：{{ sumAmount }}</el-tag></span>
              <span style="padding-left: 2px"><el-tag type="info">销售价合计：{{ sumAmtAr }}</el-tag></span>
            </el-col>
             </el-form-item> -->
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
         <span style="padding-left: 2px"><el-tag type="info">单品合计：{{ sumQty }}</el-tag></span>
         <span style="padding-left: 2px"><el-tag type="info">采购价合计：{{ sumAmount }}</el-tag></span>
         <span style="padding-left: 2px"><el-tag type="info">销售价合计：{{ sumAmtAr }}</el-tag></span>
       </el-col> -->
      <!--   <pagination v-show="page.total>0" :total="page.total" :page.sync="page.current" :limit.sync="page.pageSize" @pagination="handleQuery" />
     -->  </el-row>

    <!-- 数据列表 show-summary :summary-method="getSummaries" -->
    <el-table v-loading="loading" :data="page.records" height="550" highlight-current-row @selection-change="handleSelectionChange" @sort-change="handleSortChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="汇总年月"  prop="jobMonth" />
      <el-table-column label="店铺" align="center"  width="115" show-overflow-tooltip  prop="storeName" />
      <el-table-column label="商品SPU" align="center" width="115" prop="custSpuId" />
      <el-table-column label="SKU" align="center" width="115" prop="custSkuId" sortable/>
      <el-table-column label="商品名称" align="center" show-overflow-tooltip width="280" prop="cargoObjectName" />
      <el-table-column label="销售数" align="right" width="85" prop="originalSellQty" sortable />
      <el-table-column label="退单数" align="right" width="65" prop="returnQty" />
      <el-table-column label="实际数" align="right"  width="85" prop="wtCnt" sortable />
      <el-table-column label="买入价" align="right" width="115" sortable prop="amount">
        <template slot-scope="scope">
          <span>{{ Number(scope.row.amount).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="买单价" align="right" width="65" prop="rate" />
      <el-table-column label="卖出价" align="right" width="115" sortable prop="amtCur">
        <template slot-scope="scope">
          <span>{{ Number(scope.row.amtCur).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="卖单价" align="right" width="65" prop="exrate" />
      <el-table-column label="退单金额" align="right" width="115" prop="returnAmt">
        <template slot-scope="scope">
          <span>{{ Number(scope.row.returnAmt).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际卖价" align="right" width="115" prop="amtAr">
        <template slot-scope="scope">
          <span>{{ Number(scope.row.amtAr).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="差价" align="right" width="115" prop="profit">
        <template slot-scope="scope">
          <span>{{ Number(scope.row.profit).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售现金" align="right" width="115" prop="custCashPaymentAmt">
        <template slot-scope="scope">
          <span>{{ Number(scope.row.custCashPaymentAmt).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售里程" align="right" width="95" prop="custMilePaymentAmt" />

      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
         <template slot-scope="scope"> -->
      <!--  <el-button v-hasPermission="['accounting:accApSkuMonthlySettlement:update']" size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
        <el-button v-hasPermission="['accounting:accApSkuMonthlySettlement:delete']" size="mini" type="text" icon="el-icon-delete" @click="handleRemove(scope.row)">删除</el-button>
      --><!-- </template>
      </el-table-column> -->
    </el-table>

    <!-- 分页 -->

    <!-- 添加/修改对话框 -->
    <el-dialog :title="accApSkuMonthlySettlementFormDialog.title" :visible.sync="accApSkuMonthlySettlementFormDialog.visible" :close-on-click-modal="false" :before-close="resetAccApSkuMonthlySettlementFormDialog" width="500px" append-to-body>
      <el-form ref="accApSkuMonthlySettlementForm" :model="accApSkuMonthlySettlementFormData" :rules="accApSkuMonthlySettlementFormRules" label-width="80px">

        <!--   <el-form-item label="店铺:">
             <el-select v-model="accApSkuMonthlySettlementFormData.storeId" placeholder="请选择店铺编号" clearable size="small">
               <el-option v-for="option in options.storeOptions" :key="option.storeCode" :label="option.storeName" :value="option.storeCode" />
             </el-select>
           </el-form-item> -->
        <el-form-item label="汇总年月:">
          <el-select v-model="accApSkuMonthlySettlementFormData.jobMonth" filterable clearable><!-- @change="handleCheckDate" -->
            <el-option v-for="item in options.jobMonthList" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="商城:">
          <el-select v-model="accApSkuMonthlySettlementFormData.mallId" placeholder="请选择商城编号" clearable size="small">
            <el-option v-for="option in options.mallOptions" :key="option.id" :label="option.customerName" :value="option.id" />
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmAccApSkuMonthlySettlementFormDialog">确 定</el-button>
        <el-button @click="resetAccApSkuMonthlySettlementFormDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import AccApSkuMonthlySettlementApi from '@/api/accounting/AccApSkuMonthlySettlementApi'
import StoreApi from '@/api/basic/StoreApi'
import CustomerApi from '@/api/basic/CustomerApi'
import MaterialBuyPriceApi from "@/api/accounting/MaterialBuyPriceApi";
const defaultAccApSkuMonthlySettlementFormData = {
  jobMonth: null,
  storeId: '',
  mallId: ''
}
export default {
  name: 'AccApSkuMonthlySettlementList',
  data() {
    return {
      options: {
        mallOptions: [],
        storeOptions: [],
        supplierIdOptions: [], // 供应商编号字典
        jobMonthList: this.$constant.jobMonthOptions,
        sysYnTypeOptions: this.$constant.sysYnTypeOptions
      },
      queryParams: {
        storeId: null,
        mallId: null,
        payCust: null,
        status: null,
        custSkuId: null,
        custSpuId: null,
        cargoObjectName: null,
        sortProperty: null,
        sortDirection: null,
        jobMonth: null,
        jobMonthFr: null,
        jobMonthTo: null
      },
      page: {
        current: 1,
        pageSize: 20,
        total: 0,
        records: []
      },
      accApSkuMonthlySettlementFormDialog: {
        title: '',
        visible: false
      },
      accApSkuMonthlySettlementFormData: Object.assign({}, defaultAccApSkuMonthlySettlementFormData),
      accApSkuMonthlySettlementFormRules: {
      },
      loading: false,
      exportLoading: false,
      searchVisible: true,
      multipleSelection: [],
      isSingle: true,
      isMultiple: true,
      sumQty: 0, // 单品合计
      sumAmount: 0.00, // 采购价合计
      sumAmtAr: 0.00 // 销售价合计
    }
  },
  created() {
    this.initParam()
    this.loadOptions()
  },
  methods: {
    initParam() {
      this.queryParams.jobMonthFr = this.getLastMonth()
      this.queryParams.jobMonthTo = this.parseTime(new Date(), '{y}-{m}')
      //   this.queryParams.jobMonth = this.getLastMonth()
      console.log(this.queryParams)
    },
    loadOptions() {
      CustomerApi.list().then(response => {
        this.options.mallOptions = response.data
      })
      StoreApi.list().then(response => {
        this.options.storeOptions = response.data
      })
    },
    handleAdd() {
      this.openAccApSkuMonthlySettlementFormDialog()
    },
    handleRemove(row) {
      const ids = row.id || this.multipleSelection.map(item => item.id)
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return AccApSkuMonthlySettlementApi.remove(ids)
      }).then(() => {
        this.handleQuery()
        this.$message.success('删除成功')
      })
    },
    handleEdit(row) {
      const id = row.id || this.multipleSelection.map(item => item.id)[0]
      this.openAccApSkuMonthlySettlementFormDialog(id)
    },
    handleGenarate() {
      this.openGenDialog()
    },
    handleSortChange(sort) {
      if (sort.order) {
        this.queryParams.sortProperty = sort.prop
        this.queryParams.sortDirection = sort.order === 'ascending' ? 'asc' : 'desc'
      } else {
        this.queryParams.sortProperty = null
        this.queryParams.sortDirection = null
      }
      this.handleQuery()
    },
    /* handleCheckDate() {
       const params = {
         storeId: this.,
         mallId: null,
         jobMonth: null
         date: this.customerFormData.id,
         customerCode: this.customerFormData.customerCode
       }
       CustomerApi.checkCode(params).then(response => {
         if (!response.data) {
           this.$message.error('商城编码重复')
         }
       })
     }, */
    handleQuery() {
      /* if (!this.queryParams.storeId) {
         this.$message.warning('店铺不能为空')
         return false
       }
       if (!this.queryParams.custSkuId) {
         this.$message.warning('SKU不能为空')
         return false
       }
       if (!this.queryParams.custSpuId) {
         this.$message.warning('SPU不能为空')
         return false
       } */
      this.loading = true
      /* this.getReportSum() */
      AccApSkuMonthlySettlementApi.page(this.queryParams, this.page).then(response => {
        this.page.records = response.data.records
        this.page.total = response.data.total
        this.loading = false
      }, () => {
        this.loading = false
      })
    },
    getReportSum() {
      AccApSkuMonthlySettlementApi.reportSum(this.queryParams).then(response => {
        if (response.data && response.data.length > 0) {
          const reportSum = response.data[0]
          this.sumQty = Number(reportSum.sumQty).toFixed(0)
          this.sumAmount = Number(reportSum.sumAmount).toFixed(2)
          this.sumAmtAr = Number(reportSum.sumAmtAr).toFixed(2)
        }
      })
    },
    handleExport() {
      if (!this.queryParams.storeId) {
        this.$message.warning('导出操作店铺不能为空')
        return false
      }
      let that = this
      this.$confirm('是否确认导出数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        that.exportLoading = true
        return AccApSkuMonthlySettlementApi.exportData(that.queryParams)
      }).then(response => {
        that.exportLoading = false
        this.$common.download(response.data)
      }).catch(() => {
        that.exportLoading = false
      })
    },
    openAccApSkuMonthlySettlementFormDialog(id) {
      this.accApSkuMonthlySettlementFormDialog.visible = true
      if (id) {
        this.accApSkuMonthlySettlementFormDialog.title = '财务月度sku汇总-修改'
        AccApSkuMonthlySettlementApi.get(id).then(response => {
          this.accApSkuMonthlySettlementFormData = {
            ...this.accApSkuMonthlySettlementFormData,
            ...response.data
          }
        })
      } else {
        this.accApSkuMonthlySettlementFormDialog.title = '财务月度sku汇总-添加'
      }
    },
    confirmAccApSkuMonthlySettlementFormDialog() {
      this.$refs['accApSkuMonthlySettlementForm'].validate(valid => {
        if (valid) {
          if (this.accApSkuMonthlySettlementFormData.id) {
            AccApSkuMonthlySettlementApi.edit(this.accApSkuMonthlySettlementFormData).then(response => {
              this.$message.success('修改成功')
              this.resetAccApSkuMonthlySettlementFormDialog()
              this.handleQuery()
            })
          } else {
            AccApSkuMonthlySettlementApi.add(this.accApSkuMonthlySettlementFormData).then(response => {
              this.$message.success('添加成功')
              this.resetAccApSkuMonthlySettlementFormDialog()
              this.handleQuery()
            })
          }
        }
      })
    },
    resetAccApSkuMonthlySettlementFormDialog() {
      this.accApSkuMonthlySettlementFormDialog = {
        title: '',
        visible: false
      }
      this.accApSkuMonthlySettlementFormData = Object.assign({}, defaultAccApSkuMonthlySettlementFormData)
      this.resetForm('accApSkuMonthlySettlementForm')
    },
    getSummaries(param) {
      const propertys = ['originalSellQty', 'returnQty', 'wtCnt', 'amount', 'amtCur', 'returnAmt', 'amtAr', 'profit', 'custCashPaymentAmt', 'custMilePaymentAmt']
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (propertys.indexOf(column.property) !== -1) {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          }
          const noFixedPropertys = ['originalSellQty', 'returnQty', 'wtCnt', 'custMilePaymentAmt']
          if (noFixedPropertys.indexOf(column.property) !== -1) {
            sums[index] = Number(sums[index]).toFixed(0)
          } else {
            sums[index] = Number(sums[index]).toFixed(2)
          }
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      this.isSingle = selection.length !== 1
      this.isMultiple = !selection.length
    },
    resetQuery() {
      this.page.current = 1
      this.queryParams = {
        storeId: null,
        mallId: null,
        payCust: null,
        status: null,
        custSkuId: null,
        custSpuId: null,
        cargoObjectName: null,
        sortProperty: null,
        sortDirection: null,
        jobMonth: null,
        jobMonthFr: null,
        jobMonthTo: null
      }
      // this.resetForm('queryForm')
      this.handleQuery()
    }
  }
}
</script>
